<template>
  <div class="order-list-wrapper">
    <v-header ref="header" title="我的订单" :handleClick="true" @back="back">
      <p slot="right" @click="showSelectType = true" style="font-size: 18px;">{{typeLabel}}
        <i class="icon iconfont icon-down" style="font-size: 14px; color: #e2dddd;"></i>
      </p>
    </v-header>
    <tab :animate="false" :line-width="2" active-color="#1eb7a7" v-model="index">
      <tab-item class="vux-center" :selected="currentTab === item.value" v-for="(item) in tabList" @on-item-click="selectTab(item.value)" :key="item.value">{{item.label}}</tab-item>
    </tab>
    <!-- <swiper :height="swiperHeight" :show-dots="false" v-model="index">
      <swiper-item v-for="(item, index) in tabList" :key="index"> -->
        <scroll ref="scroll"
          v-if="orderList.length > 0"
          :data="orderList"
          :pullDownRefresh="true"
          :pullUpLoad="true"
          @pullingDown="onPullingDown"
          @pullingUp="onPullingUp"
          :style="{height: scrollHeight + 'px'}">
          <ul class="order-list">
            <li v-for="item in orderList" :key="item.id" class="order">
              <div class="goods-subject" @click.stop="toProduct(item)">
                <p class="goods-type">
                  <i v-if="currentType == 101" class="icon iconfont icon-hotel-b"/>
                  <i v-else-if="currentType == 102" class="icon iconfont icon-scenic-b"/>
                  <i v-else-if="currentType == 201" class="icon iconfont icon-specialty"/>
                  <i v-else-if="currentType == 202" class="icon iconfont icon-daoyou"/>
                  <i v-else-if="currentType == 203" class="icon iconfont icon-kehu-copy"/>
                  <span v-if="currentType != 203">{{item.goodsName.split('*')[0]}}</span>
                  <span v-if="currentType == 203">{{item.comsumerInfo.realName}}</span>
                </p>
                <p class="goods-status" v-if="currentTab === ''">{{item.orderStatusStr}}</p>
              </div>
              <ul class="goods-info" @click.stop="toOrderDetail(item)">
                <li  v-for="(goods, index) in item.orderGoodsList" :key="goods.goodsId" v-if="currentType == 202 || currentType == 201 || ((currentType == 101 || currentType == 102) && index < 1)">
                  <div class="goods-thumb" v-lazy:backgroundImage="goods.goodsImage"></div>
                  <div class="goods-center">
                    <p class="goods-name">{{currentType == 201 ? goods.goodsName : item.goodsName.split('*')[1]}}</p>
                    <p class="goods-desc">{{goods.goodsIntro}}</p>
                  </div>
                  <div class="goods-price">
                    <p class="price">￥<span>{{goods.goodsPrice}}</span></p>
                    <p class="number">x <span>{{goods.goodsType == 201 ? goods.goodsNum : item.orderGoodsList.length}}</span></p>
                  </div>
                </li>
                <li v-if="currentType == 203">
                  <div class="goods-thumb" v-lazy:backgroundImage="item.comsumerInfo.headUrl"></div>
                  <div class="goods-center">
                    <p class="goods-name">{{item.comsumerInfo.realName}}</p>
                    <p class="goods-desc">{{item.comsumerInfo.signature}}</p>
                  </div>
                  <div class="goods-price">
                    <p class="price">￥<span>{{item.totalAmount}}</span></p>
                    <p class="number">x <span>{{item.productNum}}</span></p>
                  </div>
                </li>
              </ul>
              <p class="goods-total">
                <span class="qr-code" v-if="currentType == 102 && item.orderStatus === 1 && item.shipStatus === 1">可查看二维码</span>
                <span style="margin-right: 8px;">共<span style="color: #000;margin: 0 3px; font-size: 15px">{{currentType == 201 ? item.productNum : item.orderGoodsList.length}}</span>{{currentType == 101 ? '间房间' : (currentType == 102 ? '张门票' : '件商品')}}</span>
                <span>合计:</span>
                <span class="price">￥<span style="font-size: 16px">{{item.totalAmount}}</span></span>
              </p>
              <ul class="btns" v-if="currentType != 203">
                <li v-if="(currentType == 102 || currentType == 201 || currentType == 202) && item.orderStatus == 0" class="active" @click.stop="toPay(item)">去支付</li>
                <li v-if="item.commentStatus === 0 && ((currentType == 101 && item.orderStatus == 5) || ((currentType == 102 || currentType == 201) && item.orderStatus == 3))" @click.stop="toComment(item.productId, item.outTradeNo, item.orderGoodsList[0].goodsImage, item.goodsType)">去评论</li>
                <li v-if="currentType == 201 && item.orderStatus === 1 && item.shipStatus === 1" @click.stop="handleConfirmStatus(item.outTradeNo)">确认收货</li>
                <li v-if="currentType == 201 && item.orderStatus === 1 && item.shipStatus === 1" @click.stop="toLogistics(item)">查看物流</li>
                <li v-if="currentType == 102 && item.orderStatus == 1" @click.stop="toRefundTicket(item.outTradeNo)">申请退票</li>
                <li v-if="currentType == 201 && item.orderStatus == 1" @click.stop="toRefundMoney(item.outTradeNo)">申请退款</li>
                <!-- <li @click="toOrderDetail(item)">订单详情</li> -->
                <li @click.stop="toProduct(item)">再来一单</li>
              </ul>
            </li>
          </ul>
        </scroll>
      <!-- </swiper-item>
    </swiper> -->
    <not-data v-if="orderList.length == 0" :tip="nullTip"></not-data>

    <actionsheet v-model="showSelectType" :menus="typeList" show-cancel @on-click-menu="toggoleType"></actionsheet>
  </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import Scroll from '@/components/scroll/scroll'
import NotData from '@/components/not-data/not-data'
import Loading from '@/components/loading/loading'
import { Tab, TabItem, Actionsheet, Swiper, SwiperItem } from 'vux'
import nativeBridge from '@/assets/js/nativeBridge'

import { localUser } from '@/assets/js/local'
import { isIphoneX } from '@/assets/js/brower'
import axios from '@/api/axiosApi'

const SCENIC_STATUS = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待支付'
  },
  {
    value: 1,
    label: '已支付'
  },
  {
    value: 2,
    label: '取消订单'
  },
  {
    value: 3,
    label: '订单完成'
  },
  {
    value: 7,
    label: '下单失败'
  },
  {
    value: 4,
    label: '发起退票'
  },
  {
    value: 5,
    label: '退票完成'
  },
  {
    value: 6,
    label: '退票失败'
  }
]
const HOTEL_STATUS = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待确认'
  },
  {
    value: 1,
    label: '已确认'
  },
  {
    value: 2,
    label: '取消中'
  },
  {
    value: 3,
    label: '已取消'
  },
  {
    value: 4,
    label: '取消失败'
  },
  {
    value: 5,
    label: '已完成'
  }
]
const SPECIALTY_STATUS = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待支付'
  },
  {
    value: 1,
    label: '已支付'
  },
  {
    value: 2,
    label: '取消订单'
  },
  {
    value: 3,
    label: '订单完成'
  },
  {
    value: 4,
    label: '发起退款'
  },
  {
    value: 5,
    label: '退款完成'
  },
  {
    value: 6,
    label: '退款失败'
  }
]
const GUIDE_STATUS = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待支付'
  },
  {
    value: 1,
    label: '已支付'
  },
  {
    value: 2,
    label: '取消订单'
  },
  {
    value: 3,
    label: '订单完成'
  },
  {
    value: 4,
    label: '发起退款'
  },
  {
    value: 5,
    label: '退款完成'
  },
  {
    value: 6,
    label: '退款失败'
  }
]
const CUSTOMER_STATUS = [
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '待支付'
  },
  {
    value: 1,
    label: '已支付'
  },
  {
    value: 2,
    label: '取消订单'
  },
  {
    value: 3,
    label: '订单完成'
  },
  {
    value: 4,
    label: '发起退款'
  },
  {
    value: 5,
    label: '退款完成'
  },
  {
    value: 6,
    label: '退款失败'
  }
]
export default {
  data () {
    return {
      index: 0,
      swiperHeight: '500px',
      customerName: '',
      loading: false,
      showSelectType: false,
      currentTab: '',
      tabList: HOTEL_STATUS,
      currentType: '102',
      typeList: [{
        value: '102',
        label: '景区',
        tab: SCENIC_STATUS
      }, {
        value: '101',
        label: '酒店',
        tab: HOTEL_STATUS
      }, {
        value: '201',
        label: '特产',
        tab: SPECIALTY_STATUS
      }, {
        value: '202',
        label: '导游',
        tab: GUIDE_STATUS
      }, {
        value: '203',
        label: '客户',
        tab: CUSTOMER_STATUS
      }],
      pageNum: 1,
      orderList: [],
      user: {}
    }
  },
  components: {
    VHeader, Tab, TabItem, Actionsheet, Scroll, NotData, Loading, Swiper, SwiperItem
  },
  computed: {
    typeLabel() {
      return this.typeList.find(o => o.value === this.currentType).label
    },
    currentTabStr () {
      return this.tabList.find(o => o.value === this.currentTab).label
    },
    nullTip() {
      if (this.currentTab === '') {
        return `目前没有${this.typeLabel}的订单哦~`
      }
      return `目前没有${this.typeLabel}的${this.currentTabStr}的订单~`
    }
  },
  created() {
    this.user = localUser.get() || {}
    this.paddingTop = 24
    if (isIphoneX()) {
      this.paddingTop = 34
      this.swiperHeight = window.innerHeight - 44 - 74 + 'px'
    } else {
      this.swiperHeight = window.innerHeight - 44 - 60 + 'px'
    }
    this.scrollHeight = window.innerHeight - 40 - this.paddingTop - 44
    const obj = this.typeList.find(o => o.value === this.$route.query.type)
    if (obj) {
      this.currentType = obj.value
      this.tabList = obj.tab
    }
    if (this.user.id != null && this.userType !== 1) {
      this.typeList = [{
        value: '102',
        label: '景区',
        tab: SCENIC_STATUS
      }, {
        value: '101',
        label: '酒店',
        tab: HOTEL_STATUS
      }, {
        value: '201',
        label: '特产',
        tab: SPECIALTY_STATUS
      }, {
        value: '202',
        label: '导游',
        tab: GUIDE_STATUS
      }]
    }
    this._getOrderList()
  },
  methods: {
    _getOrderList() {
      this.loading = true
      const statusList = this.tabList
      let buyerId
      let guiderId
      if (localUser.get().userType === '1' && this.currentType === '203') {
        guiderId = localUser.get('id')
      }
      if (this.currentType !== '203') {
        buyerId = localUser.get('id')
      }
      axios.get(this, '/v1/orders', {
        buyerId: buyerId,
        guiderId: guiderId,
        orderStatus: this.currentTab,
        pageNum: this.pageNum,
        pageSize: 10,
        goodsType: this.currentType
      }, (data) => {
        console.log(data)
        this.loading = false
        if (data.length === 0) {
          if (this.pageNum > 1) {
            this.pageNum--
            if (this.$refs.scroll) {
              this.$refs.scroll.hiddenPullUpLoad()
            }
          } else {
            this.pageNum = 1
            this.orderList = []
            if (this.$refs.scroll) {
              this.$refs.scroll.hiddenPullDown()
            }
          }
          return
        }
        data.forEach(item => {
          const status = statusList.find(o => o.value === item.orderStatus)
          if (status) {
            item.orderStatusStr = status.label
          }
        })

        if (this.pageNum > 1) {
          this.orderList = this.orderList.concat(data)
        } else {
          this.orderList = data
        }
      }, () => {
        this.loading = false
      })
    },
    back() {
      this.$router.replace('/user')
    },
    selectTab(value) {
      this.currentTab = value
      this.pageNum = 1
      this._getOrderList()
    },
    toggoleType(key, item) {
      this.currentType = item.value
      const obj = this.typeList.find(o => o.value === this.currentType)
      if (obj) {
        this.currentType = obj.value
        this.currentTab = ''
        this.tabList = obj.tab
      }
      this.pageNum = 1
      this._getOrderList()
    },
    onPullingDown() {
      this.pageNum = 1
      this._getOrderList()
    },
    onPullingUp() {
      this.pageNum++
      this._getOrderList()
    },
    // 再来一单
    toProduct(order) {
      if (order.goodsType === 101) {
        this.$router.push(`/hotel/${order.productId}`)
      } else if (order.goodsType === 102) {
        this.$router.push(`/scenic/${order.productId}`)
      } else if (order.goodsType === 201) {
        order.orderGoodsList.forEach(element => {
          element.userId = localUser.get('id')
        })
        axios.post(this, '/v1/shoppingCartList', {shoppingCartString: JSON.stringify({
          shoppingCartString: order.orderGoodsList
        })}, (data) => {
          this.$router.push('/user/shoppingcart')
        })
      } else if (order.goodsType === 202) {
        this.$router.push('/scenicGuide/' + order.orderGoodsList[0].belongToScenicId)
      }
    },
    // 跳转订单详情
    toOrderDetail(order) {
      if (order.goodsType === 101) {
        this.$router.push(`/hotelOrderDetail/${order.outTradeNo}`)
      } else if (order.goodsType === 102) {
        this.$router.push(`/scenicOrderDetail/${order.outTradeNo}`)
      } else if (order.goodsType === 201) {
        this.$router.push(`/orderDesc/${order.outTradeNo}`)
      } else if (order.goodsType === 202) {
        if (this.currentType === '203') {
          sessionStorage.setItem('goodsTypeTemp', 203)
        } else {
          sessionStorage.setItem('goodsTypeTemp', 204)
        }
        this.$router.push(`/scenicGuideOrderDetail/${order.outTradeNo}`)
      }
    },
    toPay (order) {
      nativeBridge.alipay(order.outTradeNo, ({arg, msg}) => {
        // 支付宝支付成功回调
        if (arg === 9000) {
          this.currentTab = 1
          this.pageNum = 1
          this._getOrderList()
        }
        this.$vux.toast.text(msg, 'middle')
      })
    },
    toComment(id, outTradeNo, goodsImage, type) {
      sessionStorage.setItem('outTradeNo', outTradeNo)
      sessionStorage.setItem('goodsImageEvalution', goodsImage)
      sessionStorage.setItem('goodsType', type)
      this.$router.replace('/user/evalution/' + id)
    },
    handleConfirmStatus (outTradeNo) {
      // 确认收货
      axios.post(this, '/v1/orderReceive/' + outTradeNo, null, (data) => {
        this.$vux.toast.text('收货成功', 'middle')
        this.currentTab = 3
        this.pageNum = 1
        this._getOrderList()
      })
    },
    toLogistics (item) {
      // 查看物流
      sessionStorage.setItem('shoppingImage', item.orderGoodsList[0].goodsImage)
      sessionStorage.setItem('goodsName', item.goodsName)
      this.$router.push('/user/logistics/' + item.shipNumber)
    },
    toRefundTicket(outTradeNo) {
      // 退票
      const _self = this
      this.$vux.confirm.show({
        title: '提示',
        content: '确定要退票吗？',
        onConfirm () {
          axios.put(_self, '/v1/refundScenic/' + outTradeNo, null, (data) => {
            _self.$vux.toast.text('已成功发起退票申请，请等候客服处理', 'middle')
            _self.currentTab = 4
            _self.pageNum = 1
            _self._getOrderList()
          })
        }
      })
    },
    toRefundMoney(outTradeNo) {
      // 退款
      const _self = this
      _self.$vux.confirm.show({
        title: '温馨提示',
        content: '确定要退款吗？<br>退款审核期为三天，请耐心等待',
        onConfirm () {
          axios.post(_self, '/v1/refund/' + outTradeNo, null, (data) => {
            _self.$router.push('/user/orderQuitServer')
          })
        }
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
@import '~@/assets/css/mixins.styl'

.order-list-wrapper
  position fixed
  z-index 100
  top 0
  left 0
  right 0
  bottom 0
  background $color-background
.order-list
  .order
    margin 12px 0
    border-bottom 0.5px solid #e2e2e2
    background #fff
  .goods-subject
    display flex
    justify-content space-between
    align-items center
    padding 0 16px
    .goods-type
      height 40px
      line-height 40px
      font-size 15px
      no-wrap()
      i
        color $color-theme
        margin-right 4px
      .fa-angle-right
        color #666
        margin-right 0
        margin-left 10px
        font-size 18px
    .goods-status
      color #f43e3e
      font-size 13px
      min-width 70px
      text-align right
  .goods-info
    li
      background #f9f9f9
      margin-bottom 8px
      padding 4px 16px
      display flex
      justify-content space-between
      &:last-child
        margin-bottom 0
    .goods-thumb
      min-width 75px
      width 75px
      height 75px
      background-size cover
      background-repeat no-repeat
      background-position center
    .goods-center
      width calc(100% - 169px)
      line-height 1.4
      .goods-name
        font-size 14px
        color #333
        no-wrap-n(2)
        margin-bottom 6px
      .goods-desc
        font-size 11px
        color #999
        no-wrap-n(2)
    .goods-price
      width 75px
      min-width 75px
      font-size 12px
      text-align right
      line-height 1
      .price
        color $color-theme
        margin-top 8px
        margin-bottom 12px
        span
          font-size 17px
      .number
        color #666
        span
          font-size 16px
  .goods-total
    text-align right
    color #333
    height 40px
    line-height 40px
    padding 0 16px
    font-size 12px
    .qr-code
      float left
      color #999
    .price
      color $color-theme
      span
        font-size 17px
  .btns
    display flex
    justify-content flex-end
    padding 12px 16px
    border-top 0.5px solid #e2e2e2
    li
      width 23%
      height 32px
      line-height 33px
      text-align center
      color #333
      border 0.5px solid #999
      border-radius 3px
      margin-right 8px
      font-size 14px
      &:last-child
        margin-right 0
    .active
      color #d65656
      border-color #d65656
      background #ffe8e8
</style>
